import React, { useState, useEffect } from 'react';
import { Badge, Button, Tooltip, message } from 'antd';
import { BellOutlined } from '@ant-design/icons';
import { notificationService } from '@/services/notificationService';
import NotificationCenter from './NotificationCenter';

interface NotificationBellProps {
  className?: string;
  style?: React.CSSProperties;
}

export default function NotificationBell({ className, style }: NotificationBellProps) {
  const [unreadCount, setUnreadCount] = useState(0);
  const [centerVisible, setCenterVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  // 加载未读通知数量
  const loadUnreadCount = async () => {
    try {
      setLoading(true);
      const count = await notificationService.getUnreadCount();
      setUnreadCount(count);
    } catch (error: any) {
      console.error('加载未读通知数量失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 组件初始化
  useEffect(() => {
    loadUnreadCount();
    
    // 定期刷新未读数量（每30秒）
    const interval = setInterval(loadUnreadCount, 30000);
    
    return () => clearInterval(interval);
  }, []);

  // 处理通知中心打开/关闭
  const handleCenterToggle = () => {
    setCenterVisible(!centerVisible);
  };

  // 处理未读数量变化
  const handleUnreadCountChange = (count: number) => {
    setUnreadCount(count);
  };

  return (
    <>
      <Tooltip title="通知中心">
        <Badge count={unreadCount} size="small">
          <Button
            type="text"
            icon={<BellOutlined />}
            onClick={handleCenterToggle}
            loading={loading}
            className={className}
            style={{
              fontSize: '16px',
              ...style
            }}
          />
        </Badge>
      </Tooltip>
      
      <NotificationCenter
        visible={centerVisible}
        onClose={() => setCenterVisible(false)}
        onUnreadCountChange={handleUnreadCountChange}
      />
    </>
  );
}

// 导出类型
export type { NotificationBellProps };